#!/usr/bin/python2.5
#
# Copyright (c) 2009 Digital Darkness
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Script that pulls a stored wave out and turns it into a PHP class."""

__author__ = 'omni@digitaldarkness.com (Omni Adams)'

import logging
import urllib
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
import wave_model


class MainPage(webapp.RequestHandler):
  """Handler for returning a wave as PHP."""

  def get(self, id):
    """Handle a get request.
 
    Args:
      id: Wave ID.
    """
    if not id:
      html = ('<html>'
              '<head>'
              '<title>PHPify your waves</title></head>'
              '<body>'
              '<h1>PHPify your waves</h1>'
              '<p>Add phpify@appspot.com as a participant of a '
              'wave. It will add a new blip with a URL back '
              'here with the Wave ID to see a serialized PHP '
              'version of the root blip of the wave.</p>'
              '</body>'
              '</html>')
      self.response.out.write(html)
      return

    id = urllib.unquote(id)
    query = wave_model.Wave.all()
    query.filter('wave_id =', id)
    try:
      self.response.out.write(query[0])
    except IndexError:
      msg = 'Wave "%s" not found' % id
      self.response.out.write(msg)
    except NeedIndexError, e:
      logging.error('Index error %s', e)
      msg = 'Error rendering wave %s' % id
      self.response.out.write(msg)
 

application = webapp.WSGIApplication([('/(.*)', MainPage)], debug=False)


def main():
  run_wsgi_app(application)
  

if __name__ == '__main__':
  main()
